import React, {
  useEffect,
  useState,
} from "react";
import {
  DefaultButton,
  IButtonStyles,
  IconButton,
  IStackStyles,
  mergeStyles,
  mergeStyleSets,
  OverflowSet,
  Stack,
} from "@fluentui/react";
import Alymodel from "../../mysql_interface/model";
import {
  asynccreatedcourseforum,
  asyncdelcourseforum,
  asyncselectcourseforum,
} from "../api/api";
import { toLocaleDateString } from "../utils/time";
import Wangeditor from "./wangeditor";
import { message, Modal } from "antd";

const classNames = mergeStyleSets({
  exampleRoot: {
    marginTop: "20px",
  },
  nameText: {
    fontWeight: "bold",
  },
});
const { confirm } = Modal;
type P = {
  user: Alymodel.IMuser;
  courseid: number;
  catebag: string;
  coursename: string;
};

const dianstackitem: IStackStyles = {
  root: {
    color: "#fff",
    width: "40px",
  },
};

const stylesusername: IStackStyles = {
  root: {
    color: "#fff",
    fontWeight: 700,
  },
};

const stylescontext: IStackStyles = {
  root: {
    color: "#fff",
  },
};
const iconClass = mergeStyles({
  fontSize: 22,
});
const classNamesicon = mergeStyleSets({
  deepSkyBlue: [{ color: "deepskyblue" }, iconClass],
  greenYellow: [
    { color: "greenyellow", float: "left", display: "inline-block" },
    iconClass,
  ],
  salmon: [{ color: "salmon" }, iconClass],
});

const iconbuttonstyle: IButtonStyles = {
  root: {},
  rootHovered: {
    color: "#FF8461",
  },
};

const mybtn = {
  overflowButton: {
    minWidth: "100px",
  },
  item: {
    minWidth: "100px",
  },
};

const onRenderOverflowButton = (
  overflowItems: any[] | undefined
): JSX.Element => {
  return (
    <IconButton
      size={24}
      role="menuitem"
      title="More options"
      style={{
        backgroundColor: "rgba(0,0,0,0)",
        color: "#fff",
      }}
      menuIconProps={{
        iconName: "MoreVertical",
        style: {
          fontSize: "24px",
          fontWeight: 700,
          height: 32,
          lineHeight: "32px",
          marginLeft: "22px",
        },
      }}
      menuProps={{ items: overflowItems! }}
    />
  );
};

interface CourseForumC extends Alymodel.IMcourseforum {
  children: Alymodel.IMcourseforum[];
}

const CourseForumView: React.FunctionComponent<P> = (p) => {
  const [messageApi, contextHolder] = message.useMessage();

  const [forum, setforum] = useState<CourseForumC[]>([]);
  const [context, setcontext] = useState<string>();
  const [courseforumid, setcourseforumid] = useState<number>();
  const [editorclear, seteditorclear] = useState(false);
  const [value, setvalue] = useState<string>();
  useEffect(() => {
    start();
  }, [p.courseid]);
  async function start() {
    const { rows, count } = await asyncselectcourseforum({
      courseid: p.courseid,
      state: [1, 2]
    });
    const data: CourseForumC[] = [];
    rows
      .filter((e) => !e.courseforumid)
      .forEach((v) => {
        const n = rows
          .filter((e) => e.courseforumid === v.ID)
          .sort(
            (a, b) =>
              new Date(a.createdAt || Date.now()).getTime() -
              new Date(b.createdAt || Date.now()).getTime()
          );
        data.push({ ...v, children: n });
      });
    setforum(data);
    setTimeout(() => {
      (window as any).hljs.initHighlightingOnLoad();
    }, 500);
  }

  function huifu(t?: number) {
    setcontext("");
    setcourseforumid(t);
  }

  function delclick(ID?: number) {
    if (ID) {
      confirm({
        title: "确定要删除吗",
        onOk() {
          asyncdelcourseforum({ ID })
            .then((e) => {
              messageApi.success("删除成功");
              start();
            })
            .catch((e) => {
              messageApi.error("删除失败");
            });
        },
        onCancel() {
          console.log("Cancel");
        },
      });
    }
  }

  useEffect(() => {
    start();
  }, []);

  function click() {
    asynccreatedcourseforum({
      userid: p.user.userid,
      courseid: p.courseid,
      context,
      courseforumid,
      username: p.user.username,
      headimage: p.user.headimg,
      userphonenum: String(p.user.username) + "-" + p.user.phonenum,
      catebag: p.catebag,
      coursename: `[${p.coursename}](${location.href})`,
    })
      .then((e) => {
        start().then((e) => {
          messageApi.success("提交成功");
          setcontext("");
          setcourseforumid(undefined);
          setvalue("");
          seteditorclear(!editorclear);
        });
      })
      .catch((e) => {
        messageApi.error(e);
      });
  }

  function setnewtext(newText?: string) {
    setcourseforumid(undefined);
    setcontext(newText);
  }

  return (
    <div className="container-fluid" style={{ paddingBottom: "48px" }}>
      {contextHolder}

      <div
        className="row"
        style={{ paddingBottom: "24px", borderBottom: "1px solid #c4c4c4" }}
      >
        <div style={{ width: "96px" }}>
          <img
            src={p.user.headimg}
            style={{ borderRadius: "50%" }}
            width="48"
          />
        </div>
        <div className="col">
          <Wangeditor
            height="400px"
            onChange={(editor) => setcontext(editor.getHtml())}
            clear={editorclear}
          ></Wangeditor>
        </div>
        <div style={{ width: "132px", textAlign: "right" }}>
          <DefaultButton
            disabled={!!courseforumid || !context?.length}
            styles={{
              root: {
                backgroundColor: "rgba(0,0,0,0)",
                color: "#fff",
                borderColor: "#ff8661",
              },
              rootHovered: {
                backgroundColor: "#ff8661",
                borderColor: "#ff8661",
                color: "#fff",
              },
              rootDisabled: {
                backgroundColor: "rgba(0,0,0,0)",
                color: "#fff",
                borderColor: "#8C8C8C",
              },
            }}
            onClick={() => click()}
          >
            发表评论
          </DefaultButton>
        </div>
      </div>
      {forum.map((e, key) => {
        return (
          <div
            key={key}
            className="row"
            style={{
              paddingTop: 24,
              paddingBottom: "24px",
              borderBottom: "1px solid #fff",
            }}
          >
            <div style={{ width: "96px" }}>
              <img
                width="48"
                style={{ borderRadius: "50%" }}
                src={e.headimage}
              ></img>
            </div>
            <Stack className="col">
              <Stack horizontal disableShrink>
                <Stack.Item grow styles={stylesusername}>
                  {e.username}
                </Stack.Item>
                {[
                  p.user.usertype === "Admin",
                  p.user.userid === e.userid,
                ].filter((v) => v).length ? (
                  <Stack.Item styles={dianstackitem}>
                    <OverflowSet
                      aria-label="Basic Menu Example"
                      role="menubar"
                      styles={{
                        root: {
                          textAlign: "right",
                        },
                      }}
                      items={[]}
                      overflowItems={[
                        {
                          key: "emailMessage" + key,
                          text: "删除",
                          onClick: () => delclick(e.ID),
                          styles: mybtn,
                        },
                      ]}
                      onRenderOverflowButton={onRenderOverflowButton}
                      onRenderItem={() => { }}
                      overflowSide={"start"}
                    />
                  </Stack.Item>
                ) : (
                  <></>
                )}
              </Stack>
              <Stack styles={stylescontext}>
                <div
                  dangerouslySetInnerHTML={{
                    __html: e.context ? e.context : "",
                  }}
                  style={{ marginBottom: 0, whiteSpace: "break-spaces" }}
                  className="divhtml"
                ></div>
              </Stack>

              <Stack
                horizontal
                disableShrink
                styles={{ root: { color: "#fff", marginBottom: 12 } }}
              >
                <Stack.Item grow>
                  {toLocaleDateString(e.createdAt)} &nbsp; &nbsp;{" "}
                  <DefaultButton
                    styles={{
                      root: {
                        backgroundColor: "rgba(0,0,0,0)",
                        color: "#fff",
                        borderColor: "#ff8661",
                      },
                      rootHovered: {
                        backgroundColor: "#ff8661",
                        borderColor: "#ff8661",
                        color: "#fff",
                      },
                      rootDisabled: {
                        backgroundColor: "rgba(0,0,0,0)",
                        color: "#fff",
                        borderColor: "#8C8C8C",
                      },
                    }}
                    onClick={() => huifu(e.ID)}
                  >
                    回复
                  </DefaultButton>{" "}
                </Stack.Item>
              </Stack>
              {courseforumid === e.ID ? (
                <Stack
                  horizontal
                  disableShrink
                  styles={{ root: { marginBottom: 12 } }}
                >
                  <Stack.Item grow styles={{ root: {} }}>
                    <Wangeditor
                      height="400px"
                      onChange={(editor) => setcontext(editor.getHtml())}
                      clear={editorclear}
                    ></Wangeditor>
                  </Stack.Item>
                  <Stack.Item
                    styles={{ root: { width: 132, textAlign: "right" } }}
                  >
                    <DefaultButton
                      disabled={
                        !!courseforumid &&
                        courseforumid === e.ID &&
                        !context?.length
                      }
                      styles={{
                        root: {
                          backgroundColor: "rgba(0,0,0,0)",
                          color: "#fff",
                          borderColor: "#ff8661",
                        },
                        rootHovered: {
                          backgroundColor: "#ff8661",
                          borderColor: "#ff8661",
                          color: "#fff",
                        },
                        rootDisabled: {
                          backgroundColor: "rgba(0,0,0,0)",
                          color: "#fff",
                          borderColor: "#8C8C8C",
                        },
                      }}
                      onClick={() => click()}
                    >
                      发表评论
                    </DefaultButton>
                  </Stack.Item>
                </Stack>
              ) : (
                <></>
              )}
              {e.children.map((f, k) => {
                return (
                  <Stack
                    horizontal
                    disableShrink
                    key={key + "_" + k}
                    styles={{ root: { marginBottom: 12, overflow: 'hidden' } }}
                  >
                    <Stack.Item style={{ width: "96px" }}>
                      <img
                        width="48"
                        style={{ borderRadius: "50%" }}
                        src={f.headimage}
                      ></img>
                    </Stack.Item>
                    <Stack.Item grow>
                      <Stack horizontal disableShrink>
                        <Stack.Item grow styles={stylesusername}>
                          {f.username}
                        </Stack.Item>
                        {[
                          p.user.usertype === "Admin",
                          p.user.userid === f.userid,
                        ].filter((v) => v).length ? (
                          <Stack.Item styles={dianstackitem}>
                            <OverflowSet
                              aria-label="Basic Menu Example"
                              role="menubar"
                              items={[]}
                              overflowItems={[
                                {
                                  key: "emailMessage" + key,
                                  text: "删除",
                                  onClick: () => delclick(f.ID),
                                  styles: mybtn,
                                },
                              ]}
                              onRenderOverflowButton={onRenderOverflowButton}
                              onRenderItem={() => { }}
                              overflowSide={"start"}
                            />
                          </Stack.Item>
                        ) : (
                          <></>
                        )}
                      </Stack>
                      <Stack styles={stylescontext}>
                        <div
                          dangerouslySetInnerHTML={{
                            __html: f.context ? f.context : "",
                          }}
                          style={{
                            marginBottom: 0,
                            whiteSpace: "break-spaces",
                          }}
                        ></div>
                      </Stack>
                    </Stack.Item>
                  </Stack>
                );
              })}
            </Stack>
          </div>
        );
      })}
    </div>
  );
};

export default CourseForumView;
